﻿using System.Collections;
using System.Collections.Generic;
using Const;
using UnityEngine;
using Entitas;

public class EliminationSystem : ReactiveSystem<GameEntity>
{
    public EliminationSystem(Contexts context) : base(context.game)
    {
    }

    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context)
    {
        return context.CreateCollector(GameMatcher.ComponentsEliminate);
    }

    protected override bool Filter(GameEntity entity)
    {
        return entity.hasComponentsEliminate 
               && entity.componentsEliminate.isEliminate == true;
    }

    protected override void Execute(List<GameEntity> entities)
    {

        
        List<IEntity> sameEntities = GetSameEntities(entities);
        GameEntity temp;

        foreach (IEntity entity in sameEntities)
        {
            temp=entity as GameEntity;
            //TODO:获取相同的Entities进行消除
            temp.isComponentsDestroy = true;
        }
    }
    private List<IEntity> GetSameEntities(List<GameEntity> entities)
    {
        List<IEntity> sameEntities=new List<IEntity>();

        foreach (GameEntity entity in entities)
        {
           
            if (!entity.isComponentsJudgeFormation)
            {
                
                sameEntities.Add(entity);
            }
            else
            {
                entity.isComponentsJudgeFormation = false;
            }
            int left = entity.componentsDetecteSameItem.LeftEntities.Count;
            int right = entity.componentsDetecteSameItem.RightEntities.Count;
            int up = entity.componentsDetecteSameItem.UpEntities.Count;
            int down = entity.componentsDetecteSameItem.DownEntities.Count;

            if (left + right >= 2)
            {
                sameEntities.AddRange(entity.componentsDetecteSameItem.LeftEntities);
                sameEntities.AddRange(entity.componentsDetecteSameItem.RightEntities);
            }
            
            if (up + down >= 2)
            {
                sameEntities.AddRange(entity.componentsDetecteSameItem.UpEntities);
                sameEntities.AddRange(entity.componentsDetecteSameItem.DownEntities);
            }
            
        }

        return sameEntities;
    }
}
